<template>
  <div class="product-detail">
    <nav class="navbar">
      <button class="back-btn" @click="goBack">← 返回</button>
    </nav>

    <!-- 商品信息区 -->
    <section class="product-info-section">
      <img class="product-img" :src="product.mainImage" alt="商品主图" />
      <div class="product-meta">
        <h1 class="product-title">{{ product.productName }}</h1>
        <div class="price">
          价格: ¥<span class="price-number">{{ currentPrice }}</span>
        </div>
        <div class="stock-sales">库存 {{ product.stock }} | 销量 {{ product.sale }}</div>
        <div class="service-tags">
          <span class="tag timely">准时达 | 承诺24小时内发货，超时必赔</span>
          <span class="tag guarantee">7天价保 | 买贵双倍赔</span>
        </div>
        <div class="shipping">包邮 | 免费上门退换 | 破损包退换 | 上门换新</div>

        <!-- 规格选择 + 数量加减器 -->
        <div class="spec-quantity">
          <div class="spec-group">
            <label class="spec-label">选择规格：</label>
            <div class="spec-list">
              <button
                v-for="(sku, idx) in product.skus"
                :key="sku.skuId || idx"
                :class="{ active: selectedSku === sku }"
                @click="selectedSku = sku"
              >
                {{ sku.specs }}
              </button>
            </div>
          </div>

          <div class="quantity-group">
            <label class="quantity-label">数量：</label>
            <div class="quantity-control">
              <button @click="decrement">-</button>
              <input type="number" v-model.number="quantity" min="1" placeholder="1" readonly />
              <button @click="increment">+</button>
            </div>
          </div>
        </div>

        <div class="action-buttons">
          <button class="btn buy" @click="confirmBuy">立即购买</button>
          <button class="btn cart" @click="addToCart">加入购物车</button>
        </div>
      </div>
    </section>

    <!-- 店铺信息区 -->
    <section class="shop-section">
      <img class="shop-avatar" :src="merchantInfo.dept?.businessImg" alt="店铺头像" />
      <div class="shop-info">
        <div class="shop-name">
          {{ merchantInfo.dept?.name }}
          <span class="official-tag" v-if="isOfficial">官方</span>
        </div>
        <div class="follow-info">
          <button class="follow-btn" @click="viewMerchant">进店</button>
        </div>
      </div>
    </section>

    <!-- Tab 栏（图文详情 / 评价） -->
    <div class="tab-bar">
      <div
        v-for="(tab, index) in tabs"
        :key="tab.key"
        @click="activeTab = tab.key"
        :class="{ active: activeTab === tab.key }"
        class="tab-item"
      >
        {{ tab.label }}
      </div>
    </div>

    <!-- 内容区 -->
    <div class="content">
      <template v-if="activeTab === 'detail'">
        <img class="detail-img" :src="product.detailImage" alt="图文详情" />
      </template>
      <template v-else>
        <div class="review-section">
          <!-- 评论表单 -->
          <div class="review-form">
            <div v-if="!replyTarget">
              <label>评论内容：</label>
              <textarea v-model="newComment.content" placeholder="请输入评论内容..."></textarea>
              
              <!-- 媒体上传区域（仅图片） -->
              <div class="media-upload-container">
                <label class="upload-label">上传图片：</label>
                <div class="upload-area" @click="openFilePicker">
                  <input 
                    type="file" 
                    ref="fileInput" 
                    class="file-input" 
                    accept="image/*"  
                    multiple 
                    @change="handleFileSelection"
                  >
                  <div class="upload-icon">+</div>
                  <div class="upload-text">点击上传或拖拽图片到此处</div>
                  <div class="upload-hint">支持JPG、PNG格式，最多5张图片</div>
                </div>
                
                <!-- 已选图片预览 -->
                <div class="media-preview" v-if="selectedFiles.length > 0">
                  <div v-for="(file, index) in selectedFiles" :key="index" class="media-item">
                    <!-- 仅保留图片预览 -->
                    <img :src="file.previewUrl" class="preview-img" :alt="'预览图 ' + (index + 1)">
                    <button class="remove-media" @click.stop="removeFile(index)">×</button>
                  </div>
                </div>
              </div>
              
              <button @click="postComment(0)">发布评论</button>
            </div>
            <div v-else>
              <label>回复内容：</label>
              <textarea v-model="newComment.content" placeholder="请输入回复内容..."></textarea>
              
              <!-- 回复图片上传 -->
              <div class="media-upload-container reply-upload">
                <label class="upload-label">添加图片：</label>
                <div class="upload-area" @click="openReplyFilePicker">
                  <input 
                    type="file" 
                    ref="replyFileInput" 
                    class="file-input" 
                    accept="image/*"  
                    multiple 
                    @change="handleReplyFileSelection"
                  >
                  <div class="upload-icon">+</div>
                  <div class="upload-text">点击上传图片</div>
                </div>
                
                <!-- 回复图片预览 -->
                <div class="media-preview" v-if="replyFiles.length > 0">
                  <div v-for="(file, index) in replyFiles" :key="index" class="media-item">
                    <!-- 仅保留图片预览 -->
                    <img :src="file.previewUrl" class="preview-img" :alt="'预览图 ' + (index + 1)">
                    <button class="remove-media" @click.stop="removeReplyFile(index)">×</button>
                  </div>
                </div>
              </div>
              
              <button @click="postComment(replyTarget)">回复</button>
              <button @click="cancelReply">取消</button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="comment-list" v-if="commentList.length">
            <CommentComponent 
              :comments="commentList"
              :current-user="currentUser"
              @reply="handleReply"
              @delete="deleteComment"
            />
          </div>
          <div v-else class="review-empty">暂无评价，快来发表第一条评论吧~</div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import axios from 'axios'

import CommentComponent  from '../shop/CommentComponent.vue' 
import { useAuthStore } from '@/stores/authStore'
import { addOrder } from '@/api/mall/bizOrderController'
import { addDetails } from '@/api/mall/bizOrderDetailController'
import { decreaseStock } from '@/api/mall/bizProductController'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
const authStore = useAuthStore()

import { addToCart as apiAddToCart } from '@/api/cart/bizCartController'
import { message } from 'ant-design-vue'
import { useCartStore } from '@/stores/cartStore'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const productId = route.params.goodsId
const BASE_URL = 'http://localhost:9527/mall'

const cartStore = useCartStore()



// 商品数据
const product = ref({
  productId: 0,
  sellerUserId: 0,
  productName: '',
  price: 0.0,
  status: 0,
  mainImage: '',
  deleted: 0,
  stock: 0,
  sale: 0,
  detailImage: '',
  skus: [
    {
      specs: '',
      realPrice: 0,
      id: 0,
    },
  ],
})

// 店铺数据
const merchantInfo = ref({
  userId: 0,
  username: '',
  nickname: null,
  password: '',
  email: '',
  phone: '',
  filePath: null,
  forcePasswordChange: null,
  deleted: 0,
  deptId: 0,
  dept: {
    id: 0,
    name: '',
    code: '',
    contactPhone: '',
    address: '',
    businessLicense: '',
    status: 0,
    deleted: 0,
    businessImg: ''
  }
})

// 店铺相关状态
const isOfficial = true
const isFollowed = ref(true)
const toggleFollow = () => {
  isFollowed.value = !isFollowed.value
}

// Tab 切换
const tabs = [
  { key: 'detail', label: '图文详情' },
  { key: 'review', label: '评价' },
]
const activeTab = ref('detail')

// 规格 & 数量状态
const selectedSku = ref(null)
const quantity = ref(1)

// 评论相关状态
const commentList = ref([]) // 评论列表数据
const replyTarget = ref(null) // 回复目标ID
const newComment = ref({
  score: 5,
  content: '',
  images: null, // 仅保留图片字段
})
const currentUser = ref({ userId: 1 }) // 模拟当前用户

// 图片上传相关
const fileInput = ref(null)
const replyFileInput = ref(null)
const selectedFiles = ref([]) // 评论的图片文件
const replyFiles = ref([]) // 回复的图片文件

// 数量加减方法
const increment = () => {
  if (quantity.value < product.value.stock) {
    quantity.value++
  }
}
const decrement = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

// 动态计算价格
const currentPrice = computed(() => {
  if (selectedSku.value) {
    const priceCent = Math.round(selectedSku.value.realPrice * 100)
    const totalCent = priceCent * quantity.value
    return totalCent / 100
  }
  return product.value.price || 0
})

// 数据加载后默认选中第一个规格
watch(product, (newVal) => {
  if (newVal.skus && newVal.skus.length > 0) {
    selectedSku.value = newVal.skus[0]
  }
})

// 获取商品详情
const fetchProductData = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/product/${productId}`)
    if (response.data.code === '00000') {
      product.value = response.data.data[0] || {}
      // 获取店铺信息
      if (product.value.sellerUserId) {
        await fetchMerchantInfo(product.value.sellerUserId)
      }
    }
  } catch (err) {
    console.error('商品详情接口调用失败：', err)
  }
}

// 获取店铺信息
const fetchMerchantInfo = async (sellerId) => {
  try {
    const response = await axios.get(`${BASE_URL}/user/${sellerId}`)
    if (response.data.code === '00000') {
      merchantInfo.value = response.data.data || {}
    }
  } catch (err) {
    console.error('店铺详情接口调用失败：', err)
  }
}

// 获取评论列表
const fetchComments = async () => {
  if (!product.value.productId) return;
  try {
    const res = await axios.get(`${BASE_URL}/comment/${product.value.productId}`);
    if (res.data.code === '00000') {
      const comments = res.data.data || [];
      commentList.value = comments;
    }
  } catch (err) {
    console.error('评论列表接口调用失败：', err);
  }
}

// 打开文件选择器
const openFilePicker = () => {
  fileInput.value.click()
}

const openReplyFilePicker = () => {
  replyFileInput.value.click()
}

// 处理图片选择（仅保留图片逻辑）
const handleFileSelection = (e) => {
  const files = e.target.files
  if (!files) return
  
  // 限制最多5张图片
  if (selectedFiles.value.length + files.length > 5) {
    alert('最多只能上传5张图片')
    return
  }
  
  Array.from(files).forEach(file => {
    // 仅处理图片类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件（支持JPG、PNG格式）')
      return
    }
    
    // 创建图片预览URL
    const reader = new FileReader()
    reader.onload = (event) => {
      selectedFiles.value.push({
        file,
        previewUrl: event.target.result,
        type: file.type
      })
    }
    reader.readAsDataURL(file)
  })
  
  // 清空input值，允许重复选择同一文件
  e.target.value = ''
}

// 处理回复的图片选择（仅保留图片逻辑）
const handleReplyFileSelection = (e) => {
  const files = e.target.files
  if (!files) return
  
  // 回复限制最多3张图片
  if (replyFiles.value.length + files.length > 3) {
    alert('回复最多只能上传3张图片')
    return
  }
  
  Array.from(files).forEach(file => {
    // 仅处理图片类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件（支持JPG、PNG格式）')
      return
    }
    
    // 创建图片预览URL
    const reader = new FileReader()
    reader.onload = (event) => {
      replyFiles.value.push({
        file,
        previewUrl: event.target.result,
        type: file.type
      })
    }
    reader.readAsDataURL(file)
  })
  
  e.target.value = ''
}

// 移除图片
const removeFile = (index) => {
  selectedFiles.value.splice(index, 1)
}

const removeReplyFile = (index) => {
  replyFiles.value.splice(index, 1)
}

// 上传图片到服务器并获取URL（仅处理图片）
const uploadFiles = async (files) => {
  if (!files || files.length === 0) return { images: [] }
  
  const formData = new FormData()
  files.forEach(item => {
    formData.append('file', item.file)
  })
  
  try {
    const res = await axios.post(`${BASE_URL}/minio/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.data.code === '00000') {
      // 仅收集图片URL
      return { 
        images: res.data.data
      }
    }
  } catch (err) {
    console.error('图片上传失败：', err)
    alert('图片上传失败，请重试')
    return null
  }
}

// 发布评论/回复（仅包含图片）
const postComment = async (parentId) => {
  if (!newComment.value.content.trim() && selectedFiles.value.length === 0 && replyFiles.value.length === 0) {
    alert('请输入评论内容或上传图片')
    return
  }
  
  // 上传图片
  const filesToUpload = parentId ? replyFiles.value : selectedFiles.value
  const uploadResult = await uploadFiles(filesToUpload)
  
  if (uploadResult === null) {
    return // 上传失败
  }
  
  const bizProductReview = {
    productId: product.value.productId,
    skuId: selectedSku.value?.id || null,
    userId: currentUser.value.userId,
    score: newComment.value.score,
    content: newComment.value.content.trim(),
    parentId,
    images: uploadResult.images, // 仅传递图片URL
  }

  try {
    const res = await axios.post(`${BASE_URL}/comment/add`, bizProductReview)
    if (res.data.code === '00000') {
      await fetchComments() // 刷新评论列表
      replyTarget.value = null 
      newComment.value.content = ''
      // 清空已选图片
      selectedFiles.value = []
      replyFiles.value = []
    }
  } catch (err) {
    console.error('发布评论接口调用失败：', err)
  }
}

// 删除评论
const deleteComment = async (commentId) => {
  if (!confirm('确定删除该评论吗？')) return

  try {
    const res = await axios.delete(`${BASE_URL}/comment/${commentId}`)
    if (res.data.code === '00000') {
      await fetchComments() // 刷新评论列表
    }
  } catch (err) {
    console.error('删除评论接口调用失败：', err)
  }
}

// 触发回复
const handleReply = (commentId) => {
  replyTarget.value = commentId
  newComment.value.content = ''
  // 清空回复的图片
  replyFiles.value = []
  // 滚动到评论输入框
  setTimeout(() => {
    document.querySelector('.review-form textarea').focus()
  }, 100)
}

// 取消回复
const cancelReply = () => {
  replyTarget.value = null
  newComment.value.content = ''
  replyFiles.value = []
}

// 监听Tab切换加载评论
watch(activeTab, (newTab) => {
  if (newTab === 'review') {
    fetchComments()
  }
})

// 进入店铺
const viewMerchant = () => {
 if (!product.value.sellerUserId) {
    alert('商家信息获取失败')
    return
  }
  router.push({
    name: 'detailMerchant',
    params: { sellerUserId: product.value.sellerUserId },
  })
}

const addToCart = async () => {

  try {

      // 准备要添加到购物车的商品信息
    const cartItem = {
      id: product.value.productId,
      title: product.value.productName,
        description: product.value.productName, // 添加描述
      cover: product.value.mainImage,
      price: selectedSku.value ? selectedSku.value.realPrice : product.value.price,
      quantity: quantity.value,
      // 可以根据需要添加其他属性
    }
    const requestDto = {
   
      productId: product.value.productId,
      quantity: quantity.value,
     specs: selectedSku.value.specs   // 添加规格信息
      
    }
    
    await apiAddToCart(requestDto)

        // 更新本地 localStorage，确保商品不会被标记为删除状态
    const userId = authStore.userInfo.id;
    if (userId) {
      const localCartKey = `localCartUpdates_${userId}`;
      const localUpdates = JSON.parse(localStorage.getItem(localCartKey) || '{}');
      
      // 确保商品不被标记为删除状态，如果之前是0（删除状态）则重置为当前数量
      if (localUpdates[product.value.productId] === 0) {
        localUpdates[product.value.productId] = quantity.value;
      } else if (localUpdates[product.value.productId]) {
        // 如果已存在则增加数量
        localUpdates[product.value.productId] += quantity.value;
      } else {
        // 如果不存在则设置为当前数量
        localUpdates[product.value.productId] = quantity.value;
      }
      
      localStorage.setItem(localCartKey, JSON.stringify(localUpdates));
    }
      // 同时更新本地状态管理
    cartStore.addToCart(cartItem)
    message.success('商品已成功添加到购物车')
    //跳转到ShopPage页面
    
  } catch (error) {
    message.error('添加到购物车失败: ' + (error.message || '未知错误'))
    console.error('添加到购物车失败:', error)
  }
}



// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchProductData()
})

const generateOrderNo = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const random = Math.random().toString(36).substring(2, 10).toUpperCase()
  return `${year}${month}${day}${random}`
}

const confirmBuy = async () => {
  if (!product.value || !authStore.userInfo.id) return
  console.log(product.value.sellerUserId );
  
  try {
    // // 1. 创建订单主表记录
    //   const stockDecreaseRes = await decreaseStock({
    //   productId: product.value.productId,
    //   quantity: quantity.value,
    //   // userId: authStore.userInfo.id,
    // })
    
    // if (!stockDecreaseRes || stockDecreaseRes.code !== '00000') {
    //   message.error(stockDecreaseRes?.message || '库存扣减失败')
    //   return
    // }
    const orderNo = generateOrderNo()
    const orderData = {
      orderNo,
      userId: authStore.userInfo.id,
      totalAmount: currentPrice.value,
      payAmount: currentPrice.value,
      orderStatus: 0, // 0-待支付
      paymentId: 1, // 假设支付方式ID为1
      paymentMethod: 'alipay' ,// 假设支付方式为支付宝
       productId: product.value.productId,
       quantity: quantity.value,
     
    }
       const stockDecreaseRequests = [{
      productId: product.value.productId,
      quantity: quantity.value
    }]
    // 调用添加订单API
      const orderRes = await addOrder({
      order: orderData, // 字段名改为 order
      stockDecreaseRequests: stockDecreaseRequests // 字段名改为 stockDecreaseRequests
    })
    if (!orderRes) throw new Error('操作过于频繁，请稍后再试')
    
    // 2. 创建订单详情记录
    const orderDetailData = [{
      orderNo,
      productId: product.value.productId,
      productName: product.value.productName,
      productImage: product.value.mainImage,
      productPrice: currentPrice.value,
      quantity: quantity.value,
      totalPrice: currentPrice.value,
      sellerUserId: product.value.sellerUserId 
    }]
    
    // 调用添加订单详情API
    const detailRes = await addDetails(orderDetailData)
    if (!detailRes) throw new Error('创建订单详情失败')
    
    // 3. 存储订单信息到sessionStorage并跳转到收银台
    sessionStorage.setItem('currentOrder', JSON.stringify({
      orderNo,
      product: {
        productId: product.value.productId,
        productName: product.value.productName,
        price: currentPrice.value,
        mainImage: product.value.mainImage
      },
      quantity: quantity.value,
      createdAt: new Date().getTime()
    }))
    
    router.push({
      path: '/cashier',
      query: { orderNo }
    })
    
    // closeBuyDialog()
  } catch (error) {
    message.error(`操作过于频繁，请稍后再试`)
    console.error('订单创建失败:', error)
  }
}
</script>

<style scoped>
/* 原有样式保持不变，仅移除视频相关样式 */
.product-detail {
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'Microsoft YaHei', sans-serif;
  padding: 0 16px;
}

/* 导航栏 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  color: #333;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border-radius: 4px;
}

.back-btn:hover {
  background-color: #f5f5f5;
}

/* 商品信息区 */
.product-info-section {
  display: flex;
  flex-wrap: wrap;
  gap: 40px;
  padding: 24px 0;
}

.product-img {
  width: 100%;
  max-width: 400px;
  height: auto;
  object-fit: cover;
  border-radius: 8px;
}

.product-meta {
  flex: 1;
  min-width: 300px;
}

.product-title {
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 16px;
  line-height: 1.4;
  color: #001529;
}

.price {
  font-size: 24px;
  color: #d00;
  margin-bottom: 12px;
}

.price-number {
  font-weight: bold;
  font-size: 28px;
}

.stock-sales {
  color: #666;
  font-size: 14px;
  margin-bottom: 16px;
}

.service-tags {
  margin-bottom: 16px;
}

.tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  color: #fff;
  font-size: 12px;
  margin-right: 8px;
  margin-bottom: 8px;
}

.timely {
  background-color: #4caf50;
}

.guarantee {
  background-color: #2196f3;
}

.shipping {
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
  line-height: 1.6;
}

/* 规格 & 数量容器 */
.spec-quantity {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 20px;
  margin: 20px 0;
  padding: 16px 0;
  border-top: 1px dashed #eee;
  border-bottom: 1px dashed #eee;
}

.spec-group {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.spec-label {
  font-size: 16px;
  color: #333;
  white-space: nowrap;
}

.spec-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.spec-list button {
  padding: 8px 16px;
  border: 1px solid #ccc;
  background: #fff;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 14px;
}

.spec-list button.active {
  background: #007bff;
  color: #fff;
  border-color: #007bff;
}

.quantity-group {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 12px;
}

.quantity-label {
  font-size: 16px;
  color: #333;
  white-space: nowrap;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.quantity-control button {
  width: 36px;
  height: 36px;
  background: #f8f8f8;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 18px;
}

.quantity-control input {
  width: 60px;
  height: 36px;
  border: none;
  text-align: center;
  font-size: 16px;
}

.quantity-control button:hover {
  background: #eee;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 24px;
}

.btn {
  flex: 1;
  padding: 14px 0;
  border: none;
  border-radius: 8px;
  color: #fff;
  cursor: pointer;
  transition: opacity 0.3s;
  font-size: 16px;
  font-weight: 500;
}

.btn:hover {
  opacity: 0.9;
  transform: translateY(-2px);
}

.buy {
  background-color: #d00;
}

.cart {
  background-color: #007bff;
}

/* 店铺信息区 */
.shop-section {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  margin-top: 16px;
}

.shop-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #eee;
}

.shop-info {
  flex: 1;
}

.shop-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.official-tag {
  background-color: #4caf50;
  color: #fff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 6px;
}

.follow-info {
  color: #666;
  font-size: 14px;
}

.follow-btn {
  background: none;
  border: 1px solid #007bff;
  color: #007bff;
  padding: 4px 12px;
  margin-left: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.follow-btn:hover {
  background-color: #f0f7ff;
}

/* Tab 栏 */
.tab-bar {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-top: 16px;
}

.tab-item {
  cursor: pointer;
  font-size: 16px;
  padding: 16px 24px;
  color: #333;
  position: relative;
}

.tab-item.active {
  color: #007bff;
  font-weight: 600;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #007bff;
}

/* 内容区 - 图文详情 */
.content {
  padding: 24px 0;
}

.detail-img {
  width: 100%;
  height: auto;
  margin-top: 12px;
  border-radius: 8px;
}

/* 内容区 - 评价部分 */
.review-section {
  padding: 16px;
}

.review-form {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.review-form textarea {
  width: 100%;
  height: 100px;
  margin: 8px 0;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: none;
  font-size: 14px;
}

.review-form textarea:focus {
  outline: none;
  border-color: #007bff;
}

.review-form button {
  margin-right: 12px;
  padding: 8px 16px;
  cursor: pointer;
  border: none;
  border-radius: 4px;
  background: #007bff;
  color: white;
  transition: all 0.3s;
}

.review-form button:nth-child(2) {
  background: #666;
}

.review-form button:hover {
  opacity: 0.9;
}

.review-empty {
  padding: 40px;
  color: #999;
  text-align: center;
  background-color: #f9f9f9;
  border-radius: 8px;
}

/* 图片上传样式 */
.media-upload-container {
  margin: 16px 0;
}

.upload-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.upload-area {
  width: 100%;
  padding: 30px 0;
  border: 2px dashed #ccc;
  border-radius: 6px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 16px;
}

.upload-area:hover {
  border-color: #007bff;
  background-color: rgba(0, 123, 255, 0.03);
}

.upload-icon {
  font-size: 32px;
  color: #999;
  margin-bottom: 8px;
  display: inline-block;
}

.upload-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.upload-hint {
  font-size: 12px;
  color: #999;
}

.file-input {
  display: none;
}

.media-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 12px;
}

.media-item {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  border: 1px solid #eee;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-media {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background-color: #ff4d4f;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  box-shadow: 0 0 0 2px white;
}

.reply-upload .upload-area {
  padding: 20px 0;
}

.reply-upload .upload-text {
  font-size: 13px;
}

.reply-upload .media-item {
  width: 80px;
  height: 80px;
}

/* 评论列表样式 */
.comment-list {
  margin-top: 16px;
}

.comment-child {
  border: 1px solid #eee;
  padding: 16px;
  margin: 12px 0;
  border-radius: 8px;
  transition: box-shadow 0.3s;
}

.comment-child:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.comment-meta {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.comment-meta span {
  display: flex;
  align-items: center;
}

.comment-content {
  margin-bottom: 16px;
  line-height: 1.6;
  font-size: 15px;
  color: #333;
}

.comment-actions {
  margin-bottom: 8px;
}

.comment-actions button {
  margin-right: 12px;
  padding: 4px 10px;
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 4px;
  background: #fff;
  transition: all 0.3s;
  font-size: 14px;
}

.comment-actions .reply-btn {
  color: #007bff;
  border-color: #007bff;
}

.comment-actions .delete-btn {
  color: #d00;
  border-color: #d00;
}

.comment-actions button:hover {
  background: #f5f5f5;
}

.comment-children {
  margin-left: 24px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #eee;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .product-info-section {
    flex-direction: column;
    gap: 20px;
  }
  
  .product-img {
    max-width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 10px;
  }
  
  .btn {
    width: 100%;
  }
  
  .tab-item {
    padding: 12px 16px;
    font-size: 14px;
  }
  
  .media-item {
    width: 80px;
    height: 80px;
  }
}
</style>